package com.gismore.jsonp;

import com.gismore.jsonp.config.AppConfig;
import com.gismore.jsonp.core.Collector;
import com.gismore.jsonp.core.SongVO;
import com.gismore.jsonp.core.Transformer;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * 应用入口
 */
public class Main {
	public static void main(String[] args) throws IOException {
		AppConfig.init();
		Logger log = LogManager.getLogger(Main.class);

		String filePath = null;
		if(args == null || args.length == 0){
			log.error("缺少参数{playlist file path}");
			return;
		}
		filePath = args[0];
		String fromDirectory = AppConfig.me().fromDirectory();
		String toDirectory = AppConfig.me().toDirectory();

		if(StringUtils.isNotBlank(fromDirectory)){
			File fromDirectoryFile = new File(fromDirectory);
			if(!fromDirectoryFile.exists()){
				log.error("播放列表文件夹配置错误：{}", toDirectory);
				return;
			}
		}
		File toDirectoryFile = new File(toDirectory);
		if(!toDirectoryFile.exists()){
			log.error("未找到目标位置：{}", toDirectory);
			return;
		}
		
		if(StringUtils.isNotBlank(fromDirectory) && !filePath.startsWith(fromDirectory)){
			filePath = fromDirectory + File.separator + filePath;
		}
		if(!filePath.endsWith(".m3u8")){
			filePath = filePath + ".m3u8";
		}
		log.info("playlist file path:{}",filePath);

		//1. 接收&解析文件
		String fileName = StringUtils.substringAfterLast(filePath, File.separator);
		File targetFile = new File(toDirectory,fileName);
		List<SongVO> songList = Collector.collect(filePath, targetFile);

		//2. 转换数据
		String targetContent = Transformer.transform(songList);
		//3. 写回目标文件
		Files.write(targetContent, targetFile, Charsets.UTF_8);

		log.info("playlist 【{}】 has been successfully transformed ^_^!", filePath);
	}
}
